package com.edroid.apkhooker.home;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

import com.chrisplus.rootmanager.RootManager;
import com.edroid.autorunner.AutoRunActivity;
import com.example.service.SystemServiceGetter;


public class AppListFragment extends BaseListFragment implements OnQueryTextListener, 
	OnCloseListener, LoaderManager.LoaderCallbacks<List<AppEntry>> {
	// This is the Adapter being used to display the list's data.
	AppListAdapter mAdapter;
	// The SearchView for doing filtering.
	SearchView mSearchView;
	// If non-null, this is the current filter the user has provided.
	String mCurFilter;
	AppListLoader mLoader;
	

	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Give some text to display if there is no data. In a real
		// application this would come from a resource.
		setEmptyText("No applications");

		// We have a menu item to show in action bar.
		setHasOptionsMenu(true);

		// Create an empty adapter we will use to display the loaded data.
		mAdapter = new AppListAdapter(getActivity());
		setListAdapter(mAdapter);

		// Start out with a progress indicator.
		setListShown(false);

		// Prepare the loader. Either re-connect with an existing one,
		// or start a new one.
		mLoader = (AppListLoader) getLoaderManager().initLoader(0, null, this);

		getListView().setFastScrollEnabled(true);
		
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}
	
	public void setShowSysApps(boolean show) {
		mLoader.setShowSysApps(show);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v == getListView()) {
			menu.add(2, 2, 0, "刷量运行");
			menu.add(2, 4, 1, "强制停止");
			menu.add(2, 0, 2, "重启应用");
			menu.add(2, 1, 3, "卸载应用");
			menu.add(2, 5, 4, "清除数据");
			menu.add(2, 6, 5, "清除缓存");
			menu.add(2, 8, 6, "Hook");
			menu.add(2, 7, 7, "unHook");
		} else {
			super.onCreateContextMenu(menu, v, menuInfo);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if(item.getGroupId() != 2)
			return false;
		
		final AppEntry appEntry = mAdapter.getItem(pressedIndex);
		final String pkg = appEntry.getPackgeName();
		

		switch (item.getItemId()) {
		case 0: {
			SystemServiceGetter.getPermissionService().forceStopPackage(pkg);
			startActivity(getActivity().getPackageManager().getLaunchIntentForPackage(pkg));
			break;
		}
		
		case 1: {
			try {
				PackageManager pm = getActivity().getPackageManager();
				final ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
				Log.w(this.getClass().getSimpleName(), "Uninstall: " + pkg
						+ "    file: " + info.sourceDir);

				if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {// 非系统
					SystemServiceGetter.getPermissionService().uninstall(pkg);
				} else {
					new AsyncTask<Void, Void, String>() {

						@Override
						protected String doInBackground(Void... params) {
							String result = RootManager.getInstance()
									.uninstallSystemApp(info.sourceDir)
									.getResult() ? "成功" : "失败";
							return result;
						}

						protected void onPostExecute(String result) {
							Toast.makeText(getActivity(),
									"删除:" + appEntry.getLabel() + result,
									Toast.LENGTH_LONG).show();
						};
					}.execute();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			// List<AppEntry> appList = mLoader.getAllApp();
			// if(mAdapter.getCount() > 0) {
			// StringBuilder sb = new StringBuilder(1024);
			//
			// for(int i=0; i<mAdapter.getCount(); i++) {
			// AppEntry app = mAdapter.getItem(i);
			//
			// if(app.mChecked) {
			// sb.append(app.getPackgeName()).append(',');
			// SystemSecretary.getInstance().uninstall(app.getPackgeName());
			// }
			// }
			//
			// System.out.println("uninstall --\n" + sb.toString());
			// }
			break;
		}

		case 2: {
			if(hook(appEntry)) {
				AutoRunActivity.run(getActivity(), pkg);
				((MainActivity)getActivity()).addToRecent(pkg);
			}
			break;
		}

		case 3: {
			if(hook(appEntry)) {
				AutoRunActivity.run(getActivity(), pkg);
				((MainActivity)getActivity()).addToRecent(pkg);
			}
			break;
		}
		
		case 4: {
			SystemServiceGetter.getPermissionService().forceStopPackage(pkg);
			break;
		}
		
		case 5: {
			SystemServiceGetter.getPermissionService().clearData(pkg);
			break;
		}

		case 6: {
			SystemServiceGetter.getPermissionService().clearCache(pkg);
			break;
		}
		
		case 7: {
		    unhook(appEntry);
		    break;
		}
		
		case 8: {
		    hook(appEntry);
		    break;
		}

		default:
			return super.onContextItemSelected(item);
		}

		return true;
	}

	public static class MySearchView extends SearchView {
		public MySearchView(Context context) {
			super(context);
		}

		// The normal SearchView doesn't clear its search text when
		// collapsed, so we will do this for it.
		@Override
		public void onActionViewCollapsed() {
			setQuery("", false);
			super.onActionViewCollapsed();
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// Place an action bar item for searching.
		MenuItem item = menu.add("Search");
		item.setIcon(android.R.drawable.ic_menu_search);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		try { //有的手机会崩溃 初始化 SearchView 
			mSearchView = new MySearchView(getActivity());
			mSearchView.setOnQueryTextListener(this);
			mSearchView.setOnCloseListener(this);
			mSearchView.setIconifiedByDefault(true);
			item.setActionView(mSearchView);
		} catch (Exception e) {
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// Called when the action bar search text has changed. Since this
		// is a simple array adapter, we can just have it do the filtering.
		mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
		mAdapter.getFilter().filter(mCurFilter);
		return true;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// Don't care about this.
		return true;
	}

	@Override
	public boolean onClose() {
		if (!TextUtils.isEmpty(mSearchView.getQuery())) {
			mSearchView.setQuery(null, true);
		}
		return true;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// Insert desired behavior here.
		Log.i("LoaderCustom", "Item clicked: " + id);

		AppEntry appEntry = mAdapter.getItem(position);
		Intent intent = getActivity().getPackageManager().getLaunchIntentForPackage(appEntry.getPackgeName());
		startActivity(intent);
	}

	@Override
	public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) {
		System.err.println("======== onCreateLoader");
		// This is called when a new Loader needs to be created. This
		// sample only has one Loader with no arguments, so it is simple.
		return new AppListLoader(getActivity());
	}

	@Override
	public void onLoadFinished(Loader<List<AppEntry>> loader, List<AppEntry> data) {
		// Set the new data in the adapter.
		mAdapter.setData(data);

		// The list should now be shown.
		if (isResumed()) {
			setListShown(true);
		} else {
			setListShownNoAnimation(true);
		}
	}

	@Override
	public void onLoaderReset(Loader<List<AppEntry>> loader) {
		// Clear the data in the adapter.
		mAdapter.setData(null);
	}
}